package com.qf.cx.simplenms.readergroup.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.qf.cx.simplenms.reader.api.ReaderManager;
import com.qf.cx.simplenms.readergroup.api.ReaderGroup;
import com.qf.cx.simplenms.readergroup.api.ReaderGroupManager;
import com.qf.cx.simplenms.readergroup.model.ReaderGroupModel;
import com.qf.cx.simplenms.readergroup.spi.ReaderGroupSpi;

public class ReaderGroupManagerImpl implements ReaderGroupManager {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private Map<String, ReaderGroupSpi> map = new HashMap<>();

	@Autowired
	private ReaderManager readerManager;

	@Override
	public synchronized ReaderGroup getReaderGroup(String name) {
		ReaderGroup readerGroup = map.get(name);
		if (readerGroup == null) {
			logger.warn("no reader group named '{}'", name);
		}
		return readerGroup;
	}

	@Override
	public synchronized void updateCache(List<ReaderGroupModel> list) {
		for (Iterator<Entry<String, ReaderGroupSpi>> it = map.entrySet().iterator(); it.hasNext();) {
			Entry<String, ReaderGroupSpi> e = it.next();

			boolean delete = true;
			for (ReaderGroupModel readerGroupModel : list) {
				if (readerGroupModel.getName().equals(e.getKey())) {
					delete = false;
					break;
				}
			}
			if (delete) {
				ReaderGroupSpi readerGroup = e.getValue();
				readerGroup.forceStop();
				it.remove();
				logger.debug("delete reader group '{}'", e.getKey());
			}
		}

		list.forEach(t -> {
			ReaderGroupSpi readerGroup = map.get(t.getName());
			if (readerGroup == null) {
				readerGroup = new ReaderGroupImpl(t, readerManager);
				map.put(t.getName(), readerGroup);
				logger.debug("add reader group '{}'", t.getName());
			} else {
				logger.debug("reader group '{}' updating", t.getName());
				readerGroup.updateReaderGroupModel(t);
				logger.debug("reader group '{}' updated", t.getName());
			}
		});

	}

	@Override
	public synchronized String dump() {
		StringBuilder sb = new StringBuilder();
		sb.append("<h1>readergroups</h1></br>");
		for (Entry<String, ReaderGroupSpi> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("</br>").append(entry.getValue().dump()).append("</br>");
		}
		sb.append("</br>");
		return sb.toString();
	}
}
